package com.gopay.bis.cib.ebank.operation;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.cib.ebank.CibMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.MD5Util;
import com.gopay.remote.bank.ICertHelper;

/**
 * 兴业银行B2C签名验签类
 * 
 * @CibB2cCertHelper.java
 * @author zhengxue
 * @2014-11-20 下午12:01:33 www.gopay.com.cn Inc.All rights reserved.
 */
public class CibB2cCertHelper implements ICertHelper {

    public String sign(BaseMessage baseMessage) throws GopayException {
        try {
            CibMessage messageB2C = (CibMessage) baseMessage;
            BankLogUtils.printB2CSignPlainLog(messageB2C);
            // 银行MAC要大写
            String signature = MD5Util.sign(messageB2C.getPlainMessage()).toUpperCase();
            BankLogUtils.printB2CSignSignatureLog(messageB2C, signature);
            return signature;
        } catch (Exception e) {
            BankLogUtils.printB2CSignExceptionLog(baseMessage, e);
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6029);
        }
    }

    public Object verify(BaseMessage baseMessage) throws GopayException {
        try {
            CibMessage messageB2C = (CibMessage) baseMessage;
            boolean isVerify;
            BankLogUtils.printB2CVerifyPlainLog(messageB2C);
            BankLogUtils.printB2CVerifySignatureLog(messageB2C, messageB2C.getMac());
            // 银行MAC要大写
            String signature = MD5Util.sign(messageB2C.getPlainMessage()).toUpperCase();
            if (signature.equals(messageB2C.getMac())) {
                // 验签成功
                isVerify = true;
                BankLogUtils.printB2CVerifyResultLog(messageB2C, isVerify);
            } else {
                // 验签失败
                isVerify = false;
                BankLogUtils.printB2CVerifyResultLog(messageB2C, isVerify);
            }
            return isVerify;
        } catch (Exception e) {
            BankLogUtils.printB2CVerifyExceptionLog(baseMessage, e);
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6031);
        }
    }

}
